'use strict';
const {
  appId,
  appSecret,
  getToken
} = require("wx-common")
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event)
  const {
    code
  } = event
  const res = await uniCloud.httpclient.request(
    "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code +
    "&grant_type=authorization_code",
    // 'https://api.weixin.qq.com/sns/jscode2session?appid=wx69b48d6eda852d25&secret=d6111d274ba5ca9112baa06074148833&js_code=' + code + '&grant_type=authorization_code', 
    {
      dataType: "json"
    }
  )
  console.log('res', res)
  const openid = res.data.openid
  const db = uniCloud.database()
  const dbRes = await db.collection("users").where({
    openid
  }).limit(1).get()
  console.log('dbRes', dbRes.affectedDocs)

  let token = getToken(openid);
  let userData
  if (dbRes.affectedDocs <= 0) {
    userData = {
      nickName: "微信用户",
      avatarUrl: "",
      gender: 0,
      country: "",
      province: "",
      city: ""
    }
    //不要泄露用户的openid
    await db.collection("users").add({
      openid: openid,
      ...userData
    });
  } else {
    userData = dbRes.data[0];

    //不要泄露用户的openid
    delete userData["openid"];
  }
  userData["token"] = token;

  return userData;
};
